package com.snail.auth.security;

import com.alibaba.fastjson.JSON;
import com.common.ResultCodeEnum;
import com.common.ResultUtil;
import com.common.util.AccessAddressUtil;
import com.common.util.DateUtil;
import com.common.util.RedisUtil;
import com.snail.auth.JwtTokenUtil;
import com.snail.auth.entity.SecurityUser;
import com.snail.auth.service.AuthMenuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @autor houyanfeng 2021/3/5
 * @description: 用户登录成功时返回给前端的数据
 */
@Component
@Slf4j
public class AjaxloginSuccessHandler implements AuthenticationSuccessHandler {
    /**
     * token超时时间
     */
    @Value("${token.expirationSeconds}")
    private int expirationSeconds;
    /**
     * token存库时间(天）
     */
    @Value("${token.validTime}")
    private int validTime;
    @Value("${token.salt}")
    private String salt;
    @Autowired
    private AuthMenuService menuService;

    // 引入 RedistUtil 工具类
    @Autowired
    private RedisUtil redisUtil;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        //获取请求的ip地址
        String currentIp = AccessAddressUtil.getIpAddress(httpServletRequest);
        // 将 ip 存在map中
        Map<String, Object> map = new HashMap<>();
//        map.put("ip", currentIp);
        // 获得主体的身份
        SecurityUser securityUser = (SecurityUser) authentication.getPrincipal();
        // 传入实体名、超时时间、主体权限，获取token
        String jwtToken = JwtTokenUtil.generateToken(securityUser.getUsername(), expirationSeconds, map, salt);

        //重置 token 的信息
        Map<String, Object> redisMap = new HashMap<>();
        redisMap.put("tokenValidTime", DateUtil.getAddDayTime(validTime));//token有效期
        redisMap.put("expirationTime", DateUtil.getAddDaySecond(expirationSeconds));//token存活时间
        redisMap.put("username", securityUser.getUsername());
        redisMap.put("userId", securityUser.getUserId().toString());
        redisMap.put("ip", currentIp);
        redisMap.put("auths", securityUser.getAuths());
        redisUtil.putHash(jwtToken, redisMap, validTime * 24 * 60 * 60);

        log.info("用户{}登录成功，信息已保存至redis", securityUser.getUsername());
        // 返回值
        response.setContentType("application/json;charset=utf-8");
        Map<String, Object> result = new HashMap<>();
        result.put("userId", securityUser.getUserId());
        result.put("userName", securityUser.getName());
        response.setHeader("authorization", jwtToken);
        response.getWriter().write(JSON.toJSONString(ResultUtil.result(result, ResultCodeEnum.LOGIN_SUCCESS)));

    }

}
